<!-- input + button(upload)，可输入图片地址或上传图片 -->
<template>
  <div class="image-input-box">
    <input ref="imageUploadInput" class="image-upload-input" type="file" accept=".jpg,.png,.gif" @change="uploadFn.handleClick">
    
    <el-input class="image-input" v-if="openInput" :modelValue="modelValue" @update:modelValue="emitBack" :disabled="disabled">
      <template #prepend>
        <el-button @click="viewFn.cutOrFillUrl"><el-icon>
          <Scissor v-if="viewData.isFullUrl" />
          <Paperclip v-else />
        </el-icon></el-button>
      </template>
    </el-input>

    <el-button class="image-upload-button" plain :icon="hiddenIcon?'':Upload" @click="uploadFn.handleUpload" :type="buttonType" :disabled="disabled">{{text}}</el-button>

    <el-button v-if="openView" class="image-view-icon" type="primary" plain :icon="View" circle :disabled="!modelValue||disabled" @click="viewFn.openImageViewer([modelValue],0)"></el-button>

  </div>
</template>

<script >
import { reactive, ref } from 'vue';
import { client, randomWord } from "@/utils/alioss";
import { Upload,View,Scissor,Paperclip} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import imageViewer from "@/components/imageViewer/index2";
export default {
  name: '',
  components:{
    Scissor,Paperclip,
  },
  props:{
    modelValue:{
      default:"",
      type: String,
    },
    text:{//按钮文本
      default:"上传图片",
      type: String,
    },
    openView: {//是否开启图片预览
      default: true,
      type: Boolean,
    },
    disabled:{
      default: false,
      type: Boolean,
    },
    openInput:{//是否开启输入框
      default: true,
      type: Boolean,
    },
    buttonType:{//按钮类型，同el-button的type
      default: "",
      type: String,
    },
    hiddenIcon:{//隐藏按钮图标
      default: false,
      type: Boolean,
    },
    isFullUrl:{
      default: null,
    }
  },
  emits:["update:modelValue"],
  setup(props,{emit}) {
    const imageUploadInput = ref(null);
    function emitBack(value){
      emit("update:modelValue",value);
    }
    const {$data:viewData,$fn:viewFn} = imageViewModule(props,emitBack);
    const {$fn: uploadFn} = uploadModule(imageUploadInput,emitBack,viewData);
    return {
      imageUploadInput,
      Upload,View,
      emitBack,
      viewData,viewFn,
      uploadFn,
    }

  }
};
const baseUrl = "https://img.qumoyugo.com";
function uploadModule(imageUploadInput,emitBack,viewData){
  const $fn={
    handleUpload() {
      imageUploadInput.value.click();
    },
    async handleClick(e) {
      const files = e.target.files||[];
      const file = files[0];
      if (!file) return;
      // 1.上传
      let res = await $fn.uploadFile(file);
      ElMessage.success("上传成功！");
      let resFileUrl = (viewData.isFullUrl?baseUrl:"")+"/"+res.name;
      emitBack(resFileUrl);
      // 清除文件
      // e.target.value="";
    },
    // 上传文件
    uploadFile(file){
      return new Promise((resolve)=>{
        let type = (()=>{
          let ms =file.name.split(".");
          return ms[ms.length-1]
        })();
        let fileName = `${randomWord(true, 20)}${Date.now()}.${type}`;
        client().put("img/"+fileName, file).then(res => {
          resolve(res);
        }).catch(err => {
          console.log(err)
        })
      });
    },
  }
  return {
    $fn,
  }
}

// 数据详情模块，包括 查看详情，大图预览,路径切换
function imageViewModule(props,emitBack){
  const $data=reactive({
    isFullUrl: true,//是否是全路径
  })
  const $fn = {
    openImageViewer(list,index){
      let imageUrl = list[0]||null;
      if(!imageUrl){return;}
      if(!$data.isFullUrl){
        imageUrl = baseUrl+imageUrl;
      }
      imageViewer({initialIndex: index,urlList: [imageUrl]});
    },
    cutOrFillUrl(){
      const reg = /^(http|https):\/\//;
      $data.isFullUrl = !$data.isFullUrl;
      if($data.isFullUrl){
        if(!reg.test(props.modelValue)) {
          emitBack(baseUrl+props.modelValue);
        }
      }else{
        if(reg.test(props.modelValue) && props.modelValue.includes(baseUrl)){
          emitBack(props.modelValue.split(baseUrl)?.[1]||"");
        }
      }
    }
  }
  
  if(props.isFullUrl===false||props.isFullUrl===true){
    $data.isFullUrl = props.isFullUrl;
  }else if(props.modelValue && !props.modelValue.includes(baseUrl)){
    $data.isFullUrl = false;
  }
  return {
    $fn,
    $data,
  }
}
</script>
<style scoped lang="scss">

.image-input-box{
  display: inline-flex;
  width: 100%;
  align-items: center;
  .image-upload-input {
    display: none;
    z-index: -1;
  }
  .image-input{
    width: calc(100% - 160px - 40px);
  }
  .image-upload-button{
    margin-left: 12px;
  }
  .image-upload-icon{
    margin-left: 12px;
  }
}
</style>